package cn.tedu.csmall.server.repo.impl; 
 /*
 @Time: 2022/8/25 10:39
 @Author:GShuai
 @File:CategoryRepositoryImpl.class
 @Software:IntelliJ IDEA
*/

import cn.tedu.csmall.server.pojo.vo.BrandDetailVO;
import cn.tedu.csmall.server.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.server.pojo.vo.CategoryDetailVO;
import cn.tedu.csmall.server.pojo.vo.CategoryListItemVO;
import cn.tedu.csmall.server.repo.ICategoryRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class CategoryRepositoryImpl implements ICategoryRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    public CategoryRepositoryImpl() {
        log.debug("创建数据访问对象：CategoryRepositoryImpl");
    }

    @Override
    public void put(CategoryDetailVO categoryDetailVO) {
        String key = KEY_PREFIX_BRAND_ITEM + categoryDetailVO.getId();
        redisTemplate.opsForValue().set(key,categoryDetailVO);
    }

    @Override
    public CategoryDetailVO get(Long id) {
        String key = KEY_PREFIX_BRAND_ITEM +id;
        Serializable serializable = redisTemplate.opsForValue().get(key);
        if(serializable != null){
            if (serializable instanceof BrandDetailVO){
                return (CategoryDetailVO) serializable;
            }
            return  null;
        }
        return null;
    }

    @Override
    public void deleteItem(Long id) {

    }

    @Override
    public void putList(List<CategoryListItemVO> list) {
        log.debug("向Redis中写入品牌列表数据：{}", list);
        for (CategoryListItemVO categoryListItemVO : list) {
            redisTemplate.opsForList().rightPush(KEY_BRAND_LIST, categoryListItemVO);
        }
    }

    @Override
    public List<CategoryListItemVO> getList() {
        log.debug("即将从Redis中读取品牌列表数据……");
        List<Serializable> list = redisTemplate.opsForList().range(KEY_BRAND_LIST, 0, -1);
        List<CategoryListItemVO> brands = new ArrayList<>();
        for (Serializable serializable : list) {
            brands.add((CategoryListItemVO) serializable);
        }
        log.debug("从Redis中读取到的品牌列表：{}", brands);
        return brands;
    }

    @Override
    public void deleteList() {
    }
}
